package com.yisu.expressway.ewf.web.springmvc;

import com.yisu.expressway.ewf.common.Constants;
import com.yisu.expressway.ewf.common.exception.StageException;
import com.yisu.expressway.ewf.common.web.JsonResult;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.SimpleMappingExceptionResolver;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

import static com.yisu.expressway.ewf.common.enums.ResponseCode.FAILURE;

/**
 * Created by Administrator on 2016/1/27.
 */
public class ExceptionHandlerResolver extends SimpleMappingExceptionResolver {
    public static final Logger logger = LoggerFactory.getLogger(ExceptionHandlerResolver.class);


    public ModelAndView doResolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
        if (ex != null) {
            logger.error("Request sequence : {} ,  Runtime Exception", RequestContext.getSeq(), ex);

            JsonResult jsonResult;
            if (ex instanceof StageException) {
                StageException dydException = (StageException) ex;
                int code = dydException.getCode() == null ? FAILURE.code : dydException.getCode();
                String message = StringUtils.isEmpty(dydException.getMessage()) ? FAILURE.msg : dydException.getMessage();
                jsonResult = new JsonResult(code, message);
            } else {
                jsonResult = new JsonResult(FAILURE.code, FAILURE.msg);
            }
            try {
                response.setHeader(Constants.REQUEST_RESULT_CODE, String.valueOf(FAILURE.code));
                PrintWriter printWriter = response.getWriter();
                printWriter.write(JsonCommonRender.getJsonResult(jsonResult));
                printWriter.flush();
                printWriter.close();
            } catch (Exception e) {
                logger.error("resolveException eror , e : {}",e);
            }
        }
        return null;
    }
}
